package com.ning.farm_income_back.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ning.farm_income_back.domain.*;
import com.ning.farm_income_back.dto.DistributionrecordsDto;
import com.ning.farm_income_back.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class DistributionService {

    @Autowired
    private DistributionrecordsMapper distributionrecordsMapper;
    @Autowired
    private DistributionrulesMapper distributionrulesMapper;
    @Autowired
    private ProfitpoolsMapper profitpoolsMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UserrevenueaccountsMapper userrevenueaccountsMapper;

    public PageInfo getPage(DistributionrecordsDto dto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize,"record_id desc ");

        List<DistributionrecordsDto> list =  distributionrecordsMapper.selectBy(dto);

        return new PageInfo<>(list);
    }

    public Distributionrules getRuleInfo() {
        return distributionrulesMapper.selectByPrimaryKey(1L);
    }

    public void updateRuleInfo(Distributionrules rules) {
        rules.setRuleId(1);
        rules.setEffectiveDate(new Date());
        distributionrulesMapper.updateByPrimaryKeySelective(rules);
    }

    public void executeDistribution() {
        double distribute = 0;
        Distributionrecords record = new Distributionrecords();
        record.setDistributionDate(new Date());
        record.setStatus("pending");
        //执行分配
        //从利润池中获取获取可分配资金
        Calendar calendar = Calendar.getInstance();
        int year =  calendar.get(Calendar.YEAR);
        Integer poolId = profitpoolsMapper.selectIdByYear(Integer.toString(year));
        Profitpools profitpools = profitpoolsMapper.selectByPrimaryKey(poolId.longValue());
        record.setProfitPoolId(poolId);

        if(profitpools!=null) {
            distribute = profitpools.getDistributedAmount().floatValue();
        }
        //将分配金额按照分配规则分给每个用户
        //获取分配规则,计算各种用户应获取的利润获取的利润
        Distributionrules rules = distributionrulesMapper.selectByPrimaryKey(1L);
        record.setRuleId(1);
        List<Integer> roleNum = usersMapper.selectNumByRole();
        if(rules!=null && roleNum!=null) {
            double adminProfit = distribute*rules.getAdmin()/100.00/roleNum.get(0);
            double investorProfit = distribute*rules.getInvestor()/100.00/roleNum.get(1);
            double farmerProfit = distribute*rules.getFarmer()/100.00/roleNum.get(2);
            //分配记录表，根据用户的角色为每个用户插入对应角色的利润，相当于是一种保障
            insertRecord(record,adminProfit,investorProfit,farmerProfit);
        }
    }

    private void insertRecord(Distributionrecords template,double adminProfit,double investorProfit,double farmerProfit){
        //根据管理员查询用户
        Users u = new Users();
        List<Users> list = usersMapper.selectBy(u);
        if(list!=null && !list.isEmpty()) {
            //插入信息
            for(Users user : list){
                // 每次循环创建新的Distributionrecords对象
                Distributionrecords record = new Distributionrecords();

                // 复制模板对象的公共属性
                BeanUtils.copyProperties(template, record);
                Userrevenueaccounts uc =  userrevenueaccountsMapper.selectInfoByUserId(user.getUserId());
                if(uc == null) {
                    uc = new Userrevenueaccounts();
                    uc.setUserId(user.getUserId());
                    userrevenueaccountsMapper.insert(uc);
                }


                switch (user.getRole()) {

                    case "admin":
                        record.setUserId(user.getUserId());
                        record.setReserveFund(new BigDecimal(adminProfit));
                        uc.setBalance(new BigDecimal(adminProfit));
                        userrevenueaccountsMapper.updateByPrimaryKey(uc);
                        distributionrecordsMapper.insert(record);
                        break;
                    case "farmer":
                        record.setUserId(user.getUserId());
                        record.setReserveFund(new BigDecimal(farmerProfit));
                        uc.setBalance(new BigDecimal(adminProfit));
                        userrevenueaccountsMapper.updateByPrimaryKey(uc);
                        distributionrecordsMapper.insert(record);
                        break;
                    case "investor":
                        record.setUserId(user.getUserId());
                        record.setReserveFund(new BigDecimal(investorProfit));
                        uc.setBalance(new BigDecimal(adminProfit));
                        userrevenueaccountsMapper.updateByPrimaryKey(uc);
                        distributionrecordsMapper.insert(record);
                        break;
                }
            }
        }

    }
}
